#!/usr/bin/python3
from openpyxl import load_workbook
from openpyxl.worksheet.datavalidation import DataValidation
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Style(Base_Plugin):
    """添加工作表样式插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]

        for directory_row in _directory.rows:
            if directory_row[1].row < self.project_config["通用开始行"]:
                continue

            table_description = directory_row[2].value.strip()
            if table_description in workbook.sheetnames:
                sheet = workbook[table_description]
                for row in sheet.rows:
                    if row[1].row == self.project_config["列字段开始行"] - 1:
                        for col in row:
                            if col.column != 1:
                                col.border = self.project_config["两侧边框"]
                            col.fill = self.project_config["背景色"]
                            col.font = self.project_config["前景色"]
                            col.alignment = self.project_config["文字居中"]

                self.processed += 1
        return_val = None
        if self.processed > 0:
            saved_name = r"SheetStyle.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
